#coding:utf-8
from django.http import HttpResponse,HttpResponseRedirect
import commands
from django.shortcuts import render
from django.contrib import messages




def index(request):
    if  request.user.is_authenticated():
        (status, output) = commands.getstatusoutput('bash shell/test.sh /mnt')
        tree = output.split('\n')
        list1 = []
        list2 = []
        list3 = []
        list4 = []
        for i in range(len(tree)):
            j=0
            list1.append(tree[i].split(",")[j])  # id
            list2.append(tree[i].split(",")[j+1]) # 文件名
            list3.append(tree[i].split(",")[j+2]) # 上级目录id
            list4.append(tree[i].split(",")[j+3]) # 文件的绝对路径
        tree1=""
        for i in range(len(list1)):
            if list2[i] == 'word':  #不显示word图片目录
                continue
            if list4[i] == 'dir':
                tree1+="d.add("+list1[i]+","+list3[i]+",'"+list2[i]+"');"
            else:
                if '.' in list2[i]:
                    name = list2[i].split('.')[0]
                    tree1+="d.add("+list1[i]+","+list3[i]+",'"+name+"','"+list4[i]+"');"
                else:
                    tree1+="d.add("+list1[i]+","+list3[i]+",'"+list2[i]+"','"+list4[i]+"');"

        return render(request,'index.html',{'tree1':tree1})

    else:
        return HttpResponseRedirect('/login/')


def Article(request,args):
    import docx
    import os
    import time
    import HTMLParser
    import shutil
    if '.' in args:
        format = args.split('.')[1] #文件后缀
    else:
        format = args  # 文件名
    path = "/mnt/" + args  # 文件的绝对路径
    img_list = path.split('/')[:-1]
    img_path = '/'.join(img_list)+"/word/media/"  # html转word后 图片存储路径
    if format == 'docx':   #如果是word文档
        print(img_path)
        import sys
        reload(sys)
        sys.setdefaultencoding('utf8')
        if os.path.exists(img_path):
            shutil.rmtree(img_path) # 递归删除img_path目录
        else:
            os.system('mkdir '+img_path)
        from docx2html import convert

        html_parser = HTMLParser.HTMLParser()
        doc = convert(path)  # 转换后的html 字符串
        doc = html_parser.unescape(doc)
        date = time.strftime("%Y%m%d%H%M%S",time.localtime())
        for img in os.listdir(img_path):
            if os.path.isfile(os.path.join(img_path,img)):
                doc = doc.replace(img,date+img)               
                os.rename(os.path.join(img_path,img),os.path.join(img_path,date+img))
        return HttpResponse(doc)
    elif format == 'txt':
        with open(path) as file:
            text = file.read()
        text = text.replace('\n','</br>')
        text = text.replace(' ','&nbsp&nbsp')
        return HttpResponse(text)
    else:
        with open(path) as file:
            text = file.read()
        return HttpResponse(text)




'''


def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid(): 
            user = form.cleaned_data['user']
            password = form.cleaned_data['password']
            reluser = Person.objects.get(user=user).user
            relpwd = Person.objects.get(user=user).password
            #return render(request, 'test.html',{'user':user,'password':password,'reluser':reluser})
            if user==reluser and password == relpwd:
             #messages.success(request,'登录成功')
                ret = "登录成功"
                return render(request, 'test.html',{'user':user,'password':password,'ret':ret})
            else:
                #messages.success(request,'登录失败')
                ret = "登录失败，密码错误！"
                return render(request, 'test.html',{'ret':ret})
    else:
            form = LoginForm()
            return render(request, 'login.html', {'form':form})

def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data['user']
            password = form.cleaned_data['password']
            Person.objects.create(user=user,password=password)
            #messages.success(request,'注册成功')
            ret = "注册成功"
            return render(request, 'test.html',{'ret':ret})
        else:
            form = RegisterForm()
            return render(request, 'register.html', {'form':form})
'''
